"use strict";
const co = require("co");
const tool = require("../utils/common");
const dao = require("../dao/check_in_dao");
const CSV = require("comma-separated-values");
const path = require("path");
const tmpdir = require("os").tmpdir();
const fs = require("fs");
const createCheckIn = function(req, res) {
	const client = tool.getResponseFunc(res);
	co(function*() {
		if (!req.body.participant || !req.body.phone) {
			console.error(req.body);
			throw new Error("e_params");
		}
		delete req.body._id;
		const result = yield dao.createCheckIn(req.body);
		client.success(result);
	}).catch(client.fail);
};
const downloadCheckIns = function(req, res) {
	const client = tool.getResponseFunc(res);
	co(function*() {
		const number = yield dao.countCheckIns();
		console.log(number);
		if (number > 30000) {
			throw new Error("too_many_records");
		}
		const records = yield dao.getCheckIns();
		const path = yield writeToLocalCsvFile(records);
		res.download(path);
	}).catch(client.fail);
};

const writeToLocalCsvFile = function(raws) {
	const datas = raws.map(data => {
		return [
			data.participant,
			data.company,
			data.position,
			data.phone,
			data.date.toString(),
			data.sex
		];
	});
	const csvStr = new CSV(datas, {
		header: ["与会者", "公司", "职位", "手机号", "签到日期", "性别"]
	}).encode();
	//console.log(new CSV(datas),new CSV(datas).encode());
	const fileName = path.join(tmpdir, `checkins_${Date.now()}.csv`);
	return new Promise((success, fail) => {
		fs.createWriteStream(fileName).end(csvStr, e => {
			if (e) {
				fail(e);
			} else {
				success(fileName);
			}
		});
	});
};
module.exports = {
	createCheckIn,
	downloadCheckIns
};